
//
// 130511 - AH - Created.
//

package org.japril.gim;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *   Indexes 
 *   {@link Item}s by their id property.
 * </p>
 * @author Arne Halvorsen (AH)
 */
public final class ItemsKeyMap 
{
  private final Map<Integer, Item> m_items=new HashMap<Integer, Item>();
  
  /**
   * <p>
   *   Creates empty map.
   * </p>
   */
  public ItemsKeyMap(){}
  
  /**
   * <p>
   *   Constructor.
   * </p>
   * @param items {@link Item}s to add to map.
   */
  public ItemsKeyMap(Collection<Item> items){ add(items); }
  
  /**
   * <p>
   *   Adds 
   *   {@link Item}.
   * </p>
   * @param item {@code Item} to add.
   */
  public void add(Item item)
  {
    if (item==null)
    {
      throw new NullPointerException("item");
    }
    
    m_items.put(item.getId(), item);
  }
  
  /**
   * <p>
   *   Adds
   *   {@link Item}s.
   * </p>
   * @param items {@code Item}s to add.
   */
  public void add(Collection<Item> items)
  {
    if (items==null)
    {
      throw new NullPointerException("items");
    }
    
    for (Item item : items) m_items.put(item.getId(), item);
  }
  
  /**
   * <p>
   *   Removes 
   *   {@link Item} with given id.
   * </p>
   * @param id Id of 
   *           {@link Item} to remove.
   */
  public void remove(int id){ m_items.remove(id); }
  
  /**
   * <p>
   *   Remove all
   *   {@link Item}s.
   * </p>
   */
  public void clear(){ m_items.clear(); }
  
  /**
   * <p>
   *   Gets number of
   *   {@link Item}s.
   * </p>
   * @return Count.
   */
  public int size(){ return m_items.size(); }
  
  /**
   * <p>
   *   Gets
   *   {@link Item} with given id.
   * </p>
   * @param id Id.
   * @return {@link Item} or {@code null} if not found.
   */
  public Item get(int id){ return m_items.get(id); }
  
  /**
   * <p>
   *   Tells if contains
   *   {@link Item} with given id.
   * </p>
   * @param id Id.
   * @return {@code true} if found else {@code false}.
   */
  public boolean contains(int id){ return m_items.containsKey(id); }
  
}
